package controller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"golang.org/x/crypto/bcrypt"
	"log"
	"net/http"
	"server/common"
	"server/dto"
	"server/model"
	"server/response"
	"server/utils"
	"server/vo"
)

type RegisterTemplate struct {
	Name      string `json:"name" binding:"required,max=10"`
	Telephone string `form:"telephone" binding:"required,min=10,max=10"`
	Password  string `form:"password" binding:"required,min=6"`
}

// @Summary 用户注册接口
// @Tags 用户API
// @Description 用户注册
// @Param User body	RegisterTemplate true "JSON数据"
// @Produce json
// @Success 200 {string} string  "ok"
// @Router /api/auth/register [post]
func Register(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	var requestUser = model.User{}
	ctx.Bind(&requestUser)

	name := requestUser.Name
	telephone := requestUser.Telephone
	password := requestUser.Password
	//数据验证
	if len(telephone) != 11 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "手机号必须为11位")
		return
	}
	if len(password) < 6 {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "密码不得少于6位")
		return
	}
	if len(name) == 0 {
		name = utils.RandomString(10)
	}
	log.Println(name, telephone, password)

	//判断手机号是否存在
	if isTelephoneExis(DB, telephone) {
		response.Response(ctx, http.StatusUnprocessableEntity, 422, nil, "用户已经存在")
		return
	}

	//创建用户
	hasedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		response.Response(ctx, http.StatusInternalServerError, 500, nil, "加密错误")
		return
	}

	newUser := model.User{
		Name:      name,
		Telephone: telephone,
		Password:  string(hasedPassword),
	}
	DB.Create(&newUser)

	token, err := common.ReleaseToken(newUser)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常"})
		log.Printf("token generate error: %v", err)
		return
	}

	//返回结果
	response.Success(ctx, gin.H{"token": token}, "注册成功")
}

type LoginTemplate struct {
	Password  string `form:"password"`
	Telephone string `form:"telephone"`
}

// @Summary 用户登录接口
// @Tags 用户API
// @Description 用户登录
// @Param User body	LoginTemplate true "JSON数据"
// @Produce json
// @Success 200 {string} string  "ok"
// @Router /api/auth/login [post]
func Login(ctx *gin.Context) {
	DB := common.GetDB()
	//获取参数
	var requestUser = model.User{}
	ctx.Bind(&requestUser)
	telephone := requestUser.Telephone
	password := requestUser.Password

	//数据验证
	fmt.Println(telephone, "手机号码长度", len(telephone))
	if len(telephone) != 11 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "手机号必须为11位"})
		return
	}
	if len(password) < 6 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "密码不得少于6位"})
		return
	}

	//判断手机号是否存在
	var user model.User
	DB.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		ctx.JSON(http.StatusUnprocessableEntity, gin.H{"code": 422, "msg": "用户不存在"})
		return
	}

	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "msg": "密码错误"})
		return
	}

	//发送token
	token, err := common.ReleaseToken(user)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"code": 500, "msg": "系统异常"})
		log.Printf("token generate error :%v", err)
		return
	}

	//返回结果
	response.Success(ctx, gin.H{"token": token}, "登录成功")
}

// @Summary 用户信息接口
// @Tags 用户API
// @Description 获取当前登录用户信息
// @Param Authorization	header string true "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjEsImV4cCI6MTYzOTk4MzkyNywiaWF0IjoxNjM5Mzc5MTI3LCJpc3MiOiJ0ZXN0Iiwic3ViIjoidXNlciB0b2tlbiJ9.4bdcjtAmK9ItuN7iuyMfFMu24fK6-4kPtsIyxEGbHAw"
// @Produce json
// @Success 200 {string} string  "ok"
// @Router /api/auth/info [get]
func Info(ctx *gin.Context) {
	user, _ := ctx.Get("user")
	ctx.JSON(http.StatusOK, gin.H{"code": 200, "data": gin.H{"user": dto.ToUserDto(user.(model.User))}})
}

func ShowMyLikes(ctx *gin.Context) {
	DB := common.GetDB()
	user, _ := ctx.Get("user")
	userId := user.(model.User).ID

	var myLikes []model.Like
	DB.Model(model.Like{}).Where("user_id = ?", userId).Order("created_at desc").Scan(&myLikes)

	var total int
	DB.Model(model.Like{}).Where("user_id = ?", userId).Count(&total)

	// 返回数据
	response.Success(ctx, gin.H{"myLikes": myLikes, "total": total}, "成功")
}

func UpdateUserSignature(ctx *gin.Context) {
	DB := common.GetDB()
	var requestUser vo.UpdateUserSignature
	// 数据验证
	if err := ctx.ShouldBind(&requestUser); err != nil {
		log.Print(err.Error())
		response.Fail(ctx, "数据验证错误", nil)
		return
	}
	var user model.User
	userId := ctx.Params.ByName("id")
	if DB.Where("id = ?", userId).First(&user).RecordNotFound() {
		response.Fail(ctx, "用户不存在", nil)
		return
	}

	if err := DB.Model(&user).Update(requestUser).Error; err != nil {
		response.Fail(ctx, "更新失败", nil)
		return
	}
	response.Success(ctx, gin.H{"user": user}, "更新成功")
}

func isTelephoneExis(db *gorm.DB, telephone string) bool {
	var user model.User
	db.Where("telephone=?", telephone).First(&user)
	if user.ID != 0 {
		return true
	}
	return false
}
